/*******************************************************}
{                                                       }
{       File: buffer.h                                  }
{       Created by Tsviatko Jongov                      }
{       http://tsviatko.jongov.com                      }
{       Date : 25.01.2007                               }
{                                                       }
{       CBuffer class.                                  }
{                                                       }
{*******************************************************/
#pragma once
#include <string.h>
#include <malloc.h>

typedef int BOOL;

class CBuffer
{
private:	
	char * fBuf = NULL;   // buffer for bytes  
	int fSize;     // size of buffer  
	int fLast;     // points after Last valid byte  
public:
	CBuffer(int Size)
	{
		fLast = 0;
		fSize = 0;	 
		fFirst = 0;   

		if (Size > 0) 
		{
			fBuf = (char *)malloc(Size);
			fSize = Size;
		}
	}

	~CBuffer()
	{
		if (fBuf != NULL)
		{
			free(fBuf);
			fBuf = NULL;
		}
	}


	void add(char * Data, int Size)
	{
  
		if (fLast + Size > fSize)
		{
			char * tmp = (char *)malloc(fLast + Size + 1);
			memcpy(tmp, fBuf, fLast);
			fSize = fLast+Size+1;
			free(fBuf);
			fBuf = tmp;
		}

		memcpy(fBuf + fLast, Data, Size);
		fLast += Size;
	}

	void compact()
	{
		if (fFirst > 0)
		{
			int aLen = fLast - fFirst;
			//for (int i = 0; i < aLen; ++i) {
			//	fBuf[i] = fBuf[i + fFirst];
			//}
			memmove(fBuf, fBuf + fFirst, aLen);
			fFirst = 0;
			fLast = aLen;
		}
	} 

	void reset()
	{
		fFirst = 0;
		fLast = 0;
	}
  
	int len()  
	{
		return(fLast - fFirst);  
	}

	void * head()
	{
		return fBuf + fFirst;
	}
	
	void operator=(CBuffer &temp)
	{
		if (fBuf != NULL)
		{
			free(fBuf);
			fBuf = NULL;
		}
		fBuf = (char *)malloc(temp.fSize + 1);
		strcpy(fBuf,temp.fBuf);
		
		fLast = temp.fLast;
		fSize = temp.fSize; 
		fFirst = temp.fFirst;  
	}

	int fFirst;   
};